import JSResource from './JSResource';
import {loadQuery, useRelayEnvironment} from 'react-relay/hooks';
import {Environment} from "relay-runtime";
import {useContext} from "react";
import {UserContext} from "./context/UserContext";
//import RelayEnvironment from './RelayEnvironment';
import  testSecondRouter  from './test/SecondRouter';
//import IssueDetailRoot from './issue/IssueDetailRoot';

import importedComponent from 'react-imported-component';

//嵌套路由的，这里只有一个顶级路路由点Root。
//下面代表routes[]嵌套层层的{目前两个路由的/ ;/issue/:id'}。
//下层次路由想要执行到达，必然的其上面层级的路由也必须执行代码的prepare准备数据?。
//回首页HomeRootIssuesQuery 以及 query RootQuery(两个都会触发，实际两次http请求包的。 loadQuery实际就是单独立刻请求的。
//后续地点击一条进入详情页面/issue/:id就不会再次取数据RootQuery;


/** 顶级路由配置： []顶级只能一条？？
 从react-router-config来的要求的routes必须是数组[];
 //路由特点：每一级层次都要留下render();
 //下面这个数组[{}] 顶级不能配置多个的！！
 //解决办法：每个顶级路由都必须经过一个点【查询这个用户是谁】。
 //路由注入组件，只能用URI的路径作为参数。 没配置prepare的有component路由是不需要数据独立提前加载的其它页面。
 //import注意! 首字母?大小写不敏感的，tsx和ts被认为不能同名字的。
 //loadQuery() can NOT be called during render; must!called outside of a Component's render();
 //这是非render()执行的代码，history路由变化cb()回调函数来运行loadQuery()发起后端请求读数据;
*/
function routesWrapper(environment: Environment) {
      //const {user, setUser} =没法用useContext(UserContext);
  const Component1 = importedComponent( () => import('./AuthComp'));

  return  [
    {
      component: Component1,
      //component: JSResource('AuthComp', () => import('./AuthComp')),
      prepare: (params:any)=> {
        const AuthQuery = require('./__generated__/AuthCompQuery.graphql');
        //const {user, setUser} =useContext(UserContext);
        return {
          rootQuery: loadQuery(
              environment,
              AuthQuery,
              {},
              // The fetchPolicy allows us to specify whether to render from cached
              // data if possible (store-or-network) or only fetch from network
              // (network-only).
              { fetchPolicy: 'store-or-network' },
          ),
        };
      },
      routes: [
        {
          path: '/',
          exact: true,
          /**
           * 不再用React.lazy了； 改成JSResource动态模式。资源标识名字必须确保在SPA程序内唯一性。
           * A lazy reference to the component for the home route. Note that we intentionally don't
           * use React.lazy here: that would start loading the component only when it's rendered.
           * By using a custom alternative we can start loading the code instantly. This is
           * especially useful with nested routes, where React.lazy would not fetch the
           * component until its parents code/data had loaded.
           */
          //component: JSResource('Branding', () => import('./Branding')),
          component: importedComponent( () => import('./Branding')),
          /**
           * A function to prepare the data for the `component` in parallel with loading
           * that component code. The actual data to fetch is defined by the component
           * itself - here we just reference a description of the data - the generated
           *没有用到后端数据; 不需要 prepare: (params:any) => {},
           */
        },
        {
          path: '/free/sdf',
          exact: true,
          component: importedComponent(() => import('./Branding')),
        },

        {
          path: '/login',
          exact: true,
          /**
           * 不再用React.lazy了； 改成JSResource动态模式。资源标识名字必须确保在SPA程序内唯一性。
           * A lazy reference to the component for the home route. Note that we intentionally don't
           * use React.lazy here: that would start loading the component only when it's rendered.
           * By using a custom alternative we can start loading the code instantly. This is
           * especially useful with nested routes, where React.lazy would not fetch the
           * component until its parents code/data had loaded.
           */
          component: importedComponent(() => import('./common/LoginPane')),
         },

        {
          path: '/home',
          exact: true,
          /**
           * 不再用React.lazy了； 改成JSResource动态模式。资源标识名字必须确保在SPA程序内唯一性。
           * A lazy reference to the component for the home route. Note that we intentionally don't
           * use React.lazy here: that would start loading the component only when it's rendered.
           * By using a custom alternative we can start loading the code instantly. This is
           * especially useful with nested routes, where React.lazy would not fetch the
           * component until its parents code/data had loaded.
           */
          component: importedComponent(() => import('./HomeRoot')),
          /**
           * 和代码读取的同时刻并行地加载数据，提前请求获取数据的时机，早从后端获得数据并准备好给后续界面代码显示用。
           * A function to prepare the data for the `component` in parallel with loading
           * that component code. The actual data to fetch is defined by the component
           * itself - here we just reference a description of the data - the generated
           * query.
           */
          prepare: (params:any) => {
            const IssuesQuery = require('./__generated__/HomeRootIssuesQuery.graphql');
            return {
              issuesQuery: loadQuery(
                  environment,
                  IssuesQuery,
                  {
                    owner: 'facebook',
                    name: 'relay',
                  },
                  // The fetchPolicy allows us to specify whether to render from cached
                  // data if possible (store-or-network) or only fetch from network
                  // (network-only).
                  { fetchPolicy: 'store-or-network' },
              ),
            };
          },
        },

        {
          path: '/issue/:id',
          //component: IssueDetailRoot, //有些情况() =>import('')会编译报错，改成静态加载不会报错。IssueDetailRoot
          component: importedComponent(() => import('./issue/IssueDetailRoot')),
          prepare: (params:any) => {
            const IssueDetailQuery = require('./issue/__generated__/IssueDetailRootQuery.graphql');
            return {
              issueDetailQuery: loadQuery(
                  environment,
                  IssueDetailQuery,
                  {
                    id: params.id,
                  },
                  { fetchPolicy: 'store-or-network' },
              ),
            };
          },
        },

        {
          path: '/todos',
          exact: true,
          component: importedComponent(() => import('./issue/todos/MainApp')),
          prepare: (params:any) => {
            const MainAppQuery = require('./issue/todos/__generated__/MainAppQuery.graphql');
            return {
              mainAppQuery: loadQuery(
                  environment,
                  MainAppQuery,
                  {
                    userId: "me"
                  },
                  { fetchPolicy: 'store-or-network' },
              ),
            };
          },
        },

        { ...testSecondRouter(environment) },

      ],
    }
  ];
};


//自定义路由器的模式：
//SPA顶部层次的路由表
//export default routes;  包裹，注入graphQL环境
export default routesWrapper;
